<?php

namespace app\api\controller\v2;

use app\admin\model\cms\Channels;
use app\admin\model\cms\News;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\PlazaCategorymodel;
use app\admin\model\cms\PlazaPostModel;
use app\admin\model\cms\Video;
use app\admin\model\UserGroup;
use app\common\controller\Api;
use app\admin\model\Score;
use app\common\model\Attachment;
use app\common\model\UserFavorite;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 用户
 */
class User extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = ['login', 'mobilelogin', 'getQrCodeLiveShow','transitionInvitationCode'];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //获取用户详情
    public function getUserDetails()
    {
        $user = $this->auth->getUser();//用户信息
        //$model = \app\admin\model\User::find($user['id']);//不同model是因为period_of_validity字段会自动转成时间
        $res = Db::name('user')->where('id',$user['id'])->find();
        if (!$res) {
            $this->error('用户信息不存在');
        }

        $res['permission_description']  = UserGroup::where('id',$res['group_id'])->value('permission_description') ?? '';//当前用户组的权限说明
        //隐藏字段
        unset($res['group_id'],$res['password'],$res['salt'],$res['token']);


        $res['is_period_of_validity'] = 1;//会员是否每有过期|0=否(已经过期),1=是(没过期)
        if (strlen($res['period_of_validity']) > 2){
            if(time() > floor($res['period_of_validity'] / 1000)){
                $res['is_period_of_validity'] = 0;
            }

            $res['period_of_validity'] = date('Y-m-d',floor($res['period_of_validity'] / 1000));
        }else{
            $res['period_of_validity'] = $res['period_of_validity'] == 1? '永久':'永久';
        }

        if ($res['user_image']) {
            if (substr($res['user_image'], 0, 1) === '/') {
                $res['user_image'] = obsurl($res['user_image']);
            }
        }
        if ($res['avatar']) {
            if (substr($res['avatar'], 0, 1) === '/') {
                $res['avatar'] = obsurl($res['avatar']);
            }
        }

        //获取广场帖子统计数量
        $count_list = Platepost::field('Count(id) as post_count, SUM(view) as total_views , SUM(comment_count) as comment_count ,SUM(post_favorites) as favorite_count')
            ->where('user_id', $user['id'])
            ->find();

        $comment_count = \app\common\model\Comment::where('user_id',$user['id'])
            ->where('type','bbs')
            ->count('id');//论坛-当前用户发布的评论的数量

        $my_favorites_count = UserFavorite::where('user_id', $user['id'])
//            ->where('table_name', 'plaza_post')
            ->count('id');

        $res['count_list'] = [
            'post_count' => (string)$count_list['post_count'] >= 0 ? (string)$count_list['post_count'] : 0,//论坛-数量
            'total_views' => (string)$count_list['total_views'] >= 0 ? (string)$count_list['total_views'] : 0,////论坛-浏览量
            'comment_count' => $comment_count,//论坛-当前用户发布的评论的数量
            'favorite_count' => (string)$count_list['favorite_count'] >= 0 ? (string)$count_list['favorite_count'] : 0,//论坛-收藏数
            'my_favorites_count' => (string)$my_favorites_count >= 0 ? (string)$my_favorites_count : 0,//广场帖子-我的收藏数
        ];

        $this->success('', $res);
    }

    //获取用户积分列表
    public function getScoreList()
    {
        $request = $this->request->param();
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 20;
        $user = $this->auth->getUser();//用户信息
        $score_sum = \app\admin\model\User::where('id', $user['id'])->value('score');
        $model = Score::where('user_id', $user['id'])->where('seq_flag', 1)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        $model = $model->toArray();

        $score_list = [];
        foreach ($model['data'] as $v) {
            switch ($v['change_type']) {
                case '1':
                    $change_type_text = '注册';
                    break;
                case '2':
                    $change_type_text = '发帖';
                    break;
                case '3':
                    $change_type_text = '评论';
                    break;
                case '4':
                    $change_type_text = '转发';
                    break;
                case '5':
                    $change_type_text = '收藏';
                    break;
                case '6':
                    $change_type_text = '加精';
                    break;
                case '7':
                    $change_type_text = '置顶';
                    break;
                case '8':
                    $change_type_text = '被收藏';
                    break;
                case '9':
                    $change_type_text = '被转发';
                    break;
                case '10':
                    $change_type_text = '下载附件';
                    break;
                case '11':
                    $change_type_text = '观看视频';
                    break;
                case '12':
                    $change_type_text = '积分消费';
                    break;
                case '13':
                    $change_type_text = '后台管理员修改';
                    break;
                case '14':
                    $change_type_text = '拉新';
                    break;
                default:
                    $change_type_text = '';
            }
            $score_list[] = [
                'id' => $v['id'],//
                'change_type_text' => $change_type_text,//
                'change_type' => $v['change_type'],//变动类型:1=注册,2=发帖,3=评论,4=转发,5=收藏,6=加精,7=置顶,8=被收藏,9=被转发,10=下载附件'
                'seq_flag' => $v['seq_flag'],//变动方向:1=增加,2=减少
                'change_num' => $v['change_num'],//积分变动数量
                'change_time' => date('Y-m-d H:i:s', $v['change_time']),//变动时间
                'ref_sn' => $v['ref_sn'],//关联ID
                'comments' => $v['comments'],//备注
                'show_notes' => $v['show_notes'],//显示说明
            ];
        }
        $res = [
            'total' => $model['total'],
            'score_sum' => $score_sum,
            'score_list' => $score_list,
        ];
        $this->success('', $res);
    }

    //获取我的帖子列表
    public function getMyPlazaPostList()
    {
        $request = $this->request->param();
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 20;
        $user = $this->auth->getUser();//用户信息

        //我的论坛帖子
        $model = Platepost::where('user_id', $user['id'])
            ->field('id,user_id,postname as title,postcontent as content,plateid,creat_time,is_audit,file_img,file_video,file_audio,file_data')
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();

        $list = $model['data'];
        $category_name = Channels::where('id', 1)->value('name');
        foreach ($list as $k => &$v) {
            $file_img = [];
            foreach (explode(',', $v['file_img']) as $path) {
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach (explode(',', $v['file_video']) as $path) {
                $file_video[] = obsurl($path);
            }

            $file_audio = [];
            foreach (explode(',', $v['file_audio']) as $path) {
                $file_audio[] = obsurl($path);
            }

            $file_data = [];
            if ($v['file_data']){
                $attachment = Attachment::whereIn('url',$v['file_data'])->select();
                foreach ($attachment as $av) {
                    $file_data[] = [
                        'filename'=>$av['filename'],
                        'url'=>obsurl($av['url'])
                    ];
                }
            }

            $v['comment_type'] = 'bbs';//news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
            $v['post_content'] = $v['content'];
            $v['create_time'] = $v['creat_time'];
            $v['category_type'] = 'plate';
            $v['category_name'] = $category_name;
            $v['file_img'] = array_filter($file_img);//图片数组
            $v['file_img_num'] = count(array_filter($file_img));//图片数组
            $v['file_video'] = array_filter($file_video);//视频数组
            $v['file_audio'] = array_filter($file_audio);//音频数组
            $v['file_data'] = array_filter($file_data);//文件数组
            unset($v['creat_time'], $v['plateid']);
        }
        $res = [
            'total' => $model['total'],
            'list' => $list,
        ];
        $this->success('', $res);
    }

    //获取我的收藏列表
    public function getMyFavorite()
    {
        $request = $this->request->param();
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 20;
        $user = $this->auth->getUser();//用户信息
        $table_name = $request['table_name'];//分类标识,内容以前所在表,不带前缀|news:新闻,plaza_post:广场,video:视频,plate_post:论坛

        $table_name_arr = ['news', 'plaza_post', 'video', 'plate_post'];
//        if (!in_array($table_name, $table_name_arr)) {
//            $this->error('分类标识不正确');
//        }

        $object_id = UserFavorite::where('user_id', $user['id'])
            ->where('table_name', $table_name)
            ->where('object_id', '>', 0)
            ->order('id', 'desc')
            ->column('object_id');


        switch ($table_name) {
            //新闻
            case 'news':
                $this->getMyFavoriteNews($object_id, $page, $limit);
                break;
            //广场
            case 'plaza_post':
                $this->getMyFavoritePlazaPost($object_id, $page, $limit);
                break;
            //视频
            case 'video':
                $this->getMyFavoriteVideo($object_id, $page, $limit);
                break;
            //论坛
            case 'plate_post':
                $this->getMyFavoritePlatePost($object_id, $page, $limit);
                break;
            default:
                $this->success('', []);
        }


    }

    //获取个人新闻收藏
    private function getMyFavoriteNews($object_id, $page, $limit)
    {
        $model = News::whereIn('id', $object_id);
        $model = $model->with(['user'])->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();

        foreach ($model['data'] as $v) {
            $list[] = [
                'category_type' => 'news',//类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'news',//news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],//
                'title' => $v['post_title'],//标题
                'content' => $v['post_content'],//内容
                'user_id' => $v['user_id'],//作者id
                'category_id' => $v['parent_id'],//分类id(仅为当前表自有分类id)
                'view_count' => $v['post_hits'],//查看数
                'like_count' => $v['post_like'],//点赞数
                'favorites_count' => $v['post_favorites'],//收藏数
                'forward_count' => $v['post_forward'],//转发数
                'comment_count' => $v['comment_count'],//评论数
                'is_top' => $v['is_top'],//是否置顶|0:否,1:是
                'is_jing' => $v['recommended'],//是否推荐|0:否,1:是
                'is_audit' => $v['post_status'],//是否审核/发布|0:否,1:是
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'create_time' => date('Y-m-d H:i:s', $v['create_time']),//创建时间
                'user' => $v['user']
            ];
        }
        $res = [
            'total' => $model['total'],
            'news_list' => $list ?? []
        ];

        $this->success('', $res);
    }

    //获取个人广场帖子收藏
    private function getMyFavoritePlazaPost($object_id, $page, $limit)
    {
        $model = PlazaPostModel::whereIn('id', $object_id);
        $model = $model->with(['user'])->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($model['data'] as $v) {
            $list[] = [
                'category_type' => 'plaza',//类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'plaza',//news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],//
                'title' => $v['postname'],//标题
                'content' => $v['postcontent'],//内容
                'user_id' => $v['user_id'],//作者id
                'category_id' => $v['plaza_category_id'],//分类id(仅为当前表自有分类id)
                'view_count' => $v['view'],//查看数
                'like_count' => $v['post_like'],//点赞数
                'favorites_count' => $v['post_favorites'],//收藏数
                'forward_count' => $v['post_forward'],//转发数
                'comment_count' => $v['comment_count'],//评论数
                'is_top' => $v['top'],//是否置顶|0:否,1:是
                'is_jing' => $v['is_jing'],//是否推荐|0:否,1:是
                'is_audit' => $v['is_audit'],//是否审核/发布|0:否,1:是
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'create_time' => $v['createtime'],//创建时间
                'user' => $v['user']
            ];
        }
        $res = [
            'total' => $model['total'],
            'plaza_post_list' => $list ?? []
        ];

        $this->success('', $res);
    }

    //获取个人视频帖子收藏
    private function getMyFavoriteVideo($object_id, $page, $limit)
    {
        $model = Video::whereIn('id', $object_id);
        $model = $model->with(['user'])->order('sort', 'desc')->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($model['data'] as $v) {
            if ($v['video_path']) {
                if (substr($v['video_path'], 0, 1) === '/') {
                    $v['video_path'] = obsurl($v['video_path']);
                }
            }
            if ($v['image']) {
                if (substr($v['image'], 0, 1) === '/') {
                    $v['image'] = obsurl($v['image']);
                }
            }
            $list[] = [
                'category_type' => 'video',//类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'video',//news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],//
                'title' => $v['title'],//标题
                'description' => $v['description'],//描述
                'image' => $v['image'],//封面图
                'video_path' => $v['video_path'],//视频链接
                'user_id' => $v['user_id'],//作者id
                'category_id' => $v['video_category_id'],//分类id(仅为当前表自有分类id)
                'type' => $v['type'],//类型|1:视频,2:音频
                'view_count' => $v['count_view'],//查看数
                'like_count' => $v['count_like'],//点赞数
                'favorites_count' => $v['count_favorite'],//收藏数
                'forward_count' => $v['count_forward'],//转发数
                'comment_count' => $v['count_comment'],//评论数
                'is_top' => $v['is_top'],//是否置顶|0:否,1:是
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'create_time' => $v['create_time'],//创建时间
                'user' => $v['user']
            ];
        }
        $res = [
            'total' => $model['total'],
            'video_list' => $list ?? []
        ];

        $this->success('', $res);
    }

    //获取个人论坛帖子收藏
    private function getMyFavoritePlatePost($object_id, $page, $limit)
    {
        $model = Platepost::whereIn('id', $object_id);
        $model = $model->with(['user'])->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($model['data'] as $v) {
            $list[] = [
                'category_type' => 'plate',//类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'bbs',//news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],//
                'title' => $v['postname'],//标题
                'content' => $v['postcontent'],//内容
                'user_id' => $v['user_id'],//作者id
                'category_id' => $v['plateid'],//分类id(仅为当前表自有分类id)
                'view_count' => $v['view'],//查看数
                'like_count' => $v['post_like'],//点赞数
                'favorites_count' => $v['post_favorites'],//收藏数
                'forward_count' => $v['post_forward'],//转发数
                'comment_count' => $v['comment_count'],//评论数
                'is_top' => $v['top'],//是否置顶|0:否,1:是
                'is_jing' => $v['is_jing'],//是否推荐|0:否,1:是
                'is_audit' => $v['is_audit'],//是否审核/发布|0:否,1:是
                'membership_price' => $v['membership_price'],//会员价格(元)|默认0:免费
                'create_time' => $v['creat_time'],//创建时间
                'user' => $v['user']
            ];
        }
        $res = [
            'total' => $model['total'],
            'plate_post_list' => $list ?? []
        ];

        $this->success('', $res);
    }

    //获取我的评论列表
    public function getMyCommentList()
    {
        $request = $this->request->param();
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 20;
        $user = $this->auth->getUser();//用户信息
        $type = $request['type'];//评论类型'bbs'=论坛,'news'=新闻,'video'=视频,'plaza'=广场;
        if (!in_array($type, ['page', 'bbs', 'news', 'video', 'plaza'])) {
            $this->error('评论类型不正确');
        }

        $model = \app\admin\model\cms\Comment::where('user_id', $user['id'])
            ->where('type', $type)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($model['data'] as &$v) {
            $v['create_time'] = date('Y-m-d H:i:s', $v['createtime']);
            $v['update_time'] = date('Y-m-d H:i:s', $v['updatetime']);
            unset($v['createtime'], $v['updatetime']);
        }
        $res = [
            'total' => $model['total'],
            'list' => $model['data'],
        ];
        $this->success('', $res);

    }

    //邀请链接转换邀请码
    public function transitionInvitationCode(){
        $invitation_code_key = $this->request->param('invitation_code_key','');
        if (!$invitation_code_key){
            $this->error('缺少参数');
        }
        $model = \app\admin\model\User::where('invitation_code_key',$invitation_code_key)->find();

        if (!$model){
            $this->error('用户已注销/不存在');
        }
        if (!$model['invitation_code']){
            $this->error('邀请码链接不正确');
        }

        $res['invitation_code'] = $model['invitation_code'];
        $this->success('',$res);
    }

    //更新用户信息
    public function updateUser()
    {

        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $type = $request['type'] ?? 1;//是否验证邀请码|0=不验证,1=验证
        $invitation_code = $request['invitation_code'] ?? null;//别人的邀请码

        $nickname = $this->request->param('nickname','');//用户昵称
        $existsUserNickname = $this->existsUserNickname($user['id'],$nickname);//检测用户昵称是否唯一
        if ($existsUserNickname['code'] == 500){
            $this->error($existsUserNickname['msg']);
        }

        $data = [
            'name' => $request['name'] ?? '',//用户真实姓名
            'nickname' => $request['nickname'] ?? '',//昵称
            'employer' => $request['employer'] ?? '',//就职单位
            'position' => $request['position'] ?? '',//职位
        ];

        if ($request['password'] ?? null) {
            $salt = $user['salt'];
            $data['password'] = md5(md5($request['password']) . $salt);
        }

        //头像
        if ($request['avatar_file'] ?? null){
            $data['avatar'] = $request['avatar_file'];
        }

        //名片
        if ($request['user_image_file'] ?? null){
            $data['user_image'] = $request['user_image_file'];//用户名片
            $data['user_image_upload_time'] = time();
        }


        //判断有邀请码且用户没有被邀请过
        if ($type == 1){
            if (!$invitation_code){
                $this->error('请填写邀请码');
            }
            if ($user['pid']){
                $this->error('当前用户已经被邀请');
            }
            if ($invitation_code == $user['invitation_code']){
                $this->error('邀请码不正确');
            }
            $data['pid'] = \app\admin\model\User::where('invitation_code', $invitation_code)->value('id') ?? 0;
            if (!$data['pid']) $this->error('邀请码不正确');
        }

        if (($data['user_image'] ?? null) || ($request['employer'] && $request['position'] && $request['name'])) {
            if ($user['group_id'] != 2) {
                //判断用户是否属于指定会员组
                $data['group_id'] = 2;
                $data['member_type'] = 'TrialMember';////member_type|tourist是游客、TrialMember试用会员，member正式会员
                $data['member_make_time'] = time();//会员开通时间
            }
        }

        //提取有值的字段进行更新
        $update_data = [];
        foreach ($data as $k => $v) {
            if ($v) {
                $update_data[$k] = $v;
            }
        }
        $update_data['is_perfect'] = 1;

        Db::startTrans();
        try {
            //如果提交的数据和数据库中的数据一样则$success就返回0
            $success = \app\admin\model\User::where('id', $user['id'])->update($update_data);
            //如果是邀请码注册则给邀请码的主人加积分
            if ($update_data['pid'] ?? false){
                $editScore = (new \app\api\controller\v2\Score())->editScore($update_data['pid'],$user['id'],'invite_register',1,'user');
                if ($editScore['code'] != 200){
                    Db::rollback();
                    $this->error('更新用户失败');
                }
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
        }

        if (!$success) {
            $this->error('更新用户失败');
        }
        $this->success('更新用户成功');

    }

    //获取会员分组列表
    public function getUserGroupList(){
        $user = $this->auth->getUser();//用户信息
        $user_data = \app\admin\model\User::where('id',$user['id'])->field('group_id,period_of_validity')->find();

        $user_group_id = 1;
        //判断用户会员是否会过期
        $time = time();
        if (strtotime($user_data['period_of_validity']) > $time){
            $user_group_id = $user_data['group_id'] ?? 1;//没有过期就设置成现在拥有的会员
        }

        $rules = UserGroup::where('id',$user_group_id)->value('rules');

        //查配置项1元=多少积分
        $score_exchange_rate = \app\common\model\Config::where('name','score_exchange_rate')->value('value');
        $is_charge = $this->request->param('is_charge',1);//是否收费|1:是,0:否
        //判断当前用户不是会员
        if ($user_group_id > 1 && $rules){
            //找权限的有交集的用户组
            $rules_arr = explode(',', $rules);
            $rules_arr_count = count($rules_arr);//获取当前用户拥有的菜单权限id数量
            $rules_all = UserGroup::where('is_charge', $is_charge)
                ->where('status', 'normal')
                ->where('id', '<>', $user_group_id);

            if ($is_charge) {
                $rules_all = $rules_all->where('membership_price', '>', 0);
            } else {
                $rules_all = $rules_all->where('membership_price', 0);
            }

            $rules_all = $rules_all->select();
            $res_arr = [];
            foreach($rules_all as $k=>$v){
                $rul = explode(',',$v['rules']);
                $rul_count = count($rul);
                $intersect = array_intersect($rules_arr, $rul);//数组交集
                if($intersect && $rul_count && $rules_arr_count == count($intersect)){
                    $v['membership_score'] = bcmul($v['membership_price'],$score_exchange_rate,2);
                    $res_arr[] = $v->toArray();
                }
            }
            $this->success('',$res_arr);
        }else{
            $res = UserGroup::where('is_charge',$is_charge)
                ->where('id','<>',$user_group_id)
                ->where('status','normal');
            if ($is_charge){
                $res = $res->where('membership_price','>',0);
            }else{
                $res = $res->where('membership_price',0);
            }
            $res = $res->field('id,name,membership_price,membership_expiry,permission_description,status')
                ->select();


            if (count($res)){
                foreach($res as &$v){
                    $v['membership_score'] = bcmul($v['membership_price'],$score_exchange_rate,2);
                }
            }
            $this->success('',$res);
        }
    }

    //获取用户列表
    public function getUserList(){
        $keyword = $this->request->param('keyword', '');
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        if (!$keyword){
            $this->error('请输入手机号或用户昵称');
        }
        $user = $this->auth->getUser();//用户信息

        $model = \app\admin\model\User::where('id','<>',$user['id'])
            ->where('nickname','like',"%{$keyword}%")
            ->whereOr('mobile','like',"%{$keyword}%")
            ->field('id,nickname,avatar')
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])->toArray();
        $res = [
            'total' => $model['total'],
            'list' => $model['data'],
        ];
        $this->success('',$res);
    }

    //是否存在用户昵称是否存在
    public function isExistsUserNickname($nickname = ''){
        if (!$nickname){
            $nickname = $this->request->param('nickname','');
        }

        if (!$nickname){
            $this->error('缺少用户昵称');
        }
        $user = $this->auth->getUser();//用户信息

        $existsUserNickname = $this->existsUserNickname($user['id'],$nickname);

        if ($existsUserNickname['code'] == 500) {
            $this->error('用户昵称已存在');
        }else{
            $this->success('');
        }
    }

    //检测用户名是否唯一
    private function existsUserNickname($user_id,$nickname){
        $exists = \app\admin\model\User::where('id','<>',$user_id)
            ->where('nickname',$nickname)
            ->value('id');
        $res = [
            'code'=>200,
            'msg'=>'',
        ];
        if ($exists) {
            $res['code'] = 500;
            $res['msg'] = '用户昵称已存在';
        }
        return $res;
    }

    //获取我评论过的文章(论坛帖子)
    public function getMyCommentedArticles(){
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type','bbs');//评论类型|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播,album:专辑
        $user = $this->auth->getUser();//用户信息

        $comment = Db::name('comment')->where('user_id', $user['id'])
            ->where('type', $type)
            ->order('id', 'desc')
            ->field('aid')
            ->group('aid')
            ->paginate($limit, false, ['page' => $page]);
        $tota = $comment->total();

        $aid_arr = $comment->column('aid');

        $data = Platepost::whereIn('id',$aid_arr)->with(['user'])->select();

        $arList = [];
        foreach($data as $v){

            if (!$v['user']) {
                $v['user'] = \app\admin\model\User::getSoftDeleteUser($v['user_id']);
            }

            if ($v['user']['avatar'] ?? '') {
                $v['user']['avatar'] = obsurl($v['user']['avatar']);
            }
            if ($v['file']) {
                $v['file'] = obsurl($v['file']);
            }

            $file_img = [];
            foreach (explode(',', $v['file_img']) as $path) {
                $file_img[] = obsurl($path);
            }
            $file_video = [];
            foreach (explode(',', $v['file_video']) as $path) {
                $file_video[] = obsurl($path);
            }
            $file_data = [];
            if ($v['file_data']) {
                $attachment = Attachment::whereIn('url', $v['file_data'])->select();
                foreach ($attachment as $av) {
                    $file_data[] = [
                        'filename' => $av['filename'],
                        'url' => obsurl($av['url'])
                    ];
                }
            }

            $content_arr = [
                'table_name' => 'plate_post',//点赞收藏用|内容以前所在表,不带前缀|news:新闻,plaza_post:广场,video:视频,plate_post:论坛
                'category_type' => 'plate',//查看详情用|类型|plaza:广场帖子,plate:论坛帖子,news:新闻,video:视频,live:直播,investment:投研日志
                'comment_type' => 'bbs',//发布评论用|news:新闻,bbs:论坛,video:视频,plaza:广场,live:直播
                'id' => $v['id'],
                'post_title' => $v['postname'],//标题
                'content' => $v['postcontent'],//内容
                'post_favorites' => $v['post_favorites'] ?? 0,//收藏数量
                'post_forward' => 0,//转发数量
                'membership_price' => $v['membership_price'],//会员价格|0:免费
                'user_id' => $v['user_id'],//用户id
                'avatar' => $v['user']['avatar'] ?? '',//用户头像
                'username' => $v['user']['nickname'] ?? '',//昵称
                'thumbnail' => $v['file'],//图片链接
                'is_accessory' => ($v['accessory'] ? 1 : 0),//是否存在附件|0:否,1:是
                'is_top' => $v['top'],//是否置顶|0:否
                'is_jing' => $v['is_jing'],//是否加精|0:否
//                'is_mylike' => $is_mylike ? 1 : 0,//是否喜欢|0:否
//                'is_myfavorite' => $is_myfavorite ? 1 : 0,//是否收藏|0:否
                'recommended' => $v['is_jing'],//是否推荐|0:否
//                'commentList' => $commentList,//顶级评论列表
                'comment_count' => $v['comment_count'],//评论数量
                'create_time' => $v['creat_time'],//创建时间
                'post_like' => $v['post_like'],//点赞数量
                'post_hits' => 0,//点击量
                'is_member_expire' => 0,//会员是否到期|0:否,1:是

                'file_img' => array_filter($file_img),//图片数组
                'file_img_num' => count(array_filter($file_img)),//图片数组
                'file_video' => array_filter($file_video),//视频数组
                'file_data' => array_filter($file_data),//文件数组
                'is_author' => 0,//是否为作者|0:否,1:是
            ];
            $arList[] = $content_arr;
        }


        $res = [
            'total' => $tota,
            'list' => $arList,
        ];
        $this->success('',$res);



        $user = $this->auth->getUser();//用户信息
    }


    /**
     * 统计用户信息数量
     */
    public function getUserConunt(){
        $user = $this->auth->getUser();//用户信息
        $user_id = $user['id'];
        //获取我评论过的文章(论坛帖子) 数量
        $comment_count = \app\common\model\Comment::where('user_id',$user['id'])
            ->where('type','bbs')
            ->count('id');//论坛-当前用户发布的评论的数量

        //统计我收藏别人文章的数量(视频+论坛)
        $favorite_count = UserFavorite::where('user_id',$user_id)
            ->whereIn('table_name',['video','plate_post'])
            ->count();


        //统计我发布了多少帖子(论坛)
        $plate_post_count = Platepost::where('user_id',$user_id)
            ->where('is_audit',1)
            ->count();

        $res = [
            'comment_count'=>$comment_count,
            'favorite_count'=>$favorite_count,
            'plate_post_count'=>$plate_post_count,
        ];
        $this->success('', $res);

    }
}
